const express = require("express");
const path = require("path");
const logger = require("morgan");
const moment = require("moment");
const bodyParser = require("body-parser");
const favicon = require("serve-favicon");
var progressStream = require("progress-stream");
// var ProgressBar = require("progress");
const cliProgress = require('cli-progress');
const multer = require("multer");

const webconfig = {
  port: 3001,
};

const app = express();

// logger.token("time", function (req, res) {
//   return moment().format("HH:mm:ss");
// });
// logger.token("realip", function (req, res) {
//   if (!req.ip) return "";
//   return req.ip.replace("::ffff:", "").replace("::1", "");
// });
app.use(favicon(path.join(__dirname, "public", "favicon.ico")));
// app.use(
//   logger(":time :method :status :realip :url", {
//     skip: function (req, res) {
//       return false;
//       return (
//         res.statusCode == 200 || res.statusCode == 204 || res.statusCode == 304
//       );
//     },
//   })
// );

let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./files");
  },
  filename: function (req, file, cb) {
    let ex = file.originalname.slice(file.originalname.indexOf("."));
    cb(null, new Date().valueOf() + ex);
  },
});
let fileFilter = function (req, file, cb) {
  // console.log("开始上传 ：", file.originalname);
  cb(null, true);
};
// const upload = multer({ dest: "files/" });
let upload = multer({
  storage,
  fileFilter,
}).fields([{ name: "file" }]);

// app.post("/upload", upload, function (req, res, next) {
//   console.log("上传4");
//   res.json({ msg: "ok" });
// });
const multibar = new cliProgress.MultiBar({
  clearOnComplete: false,
  hideCursor: true,
  format: ' {bar} | {filename} | {value}/{total}',
}, cliProgress.Presets.shades_grey);
app.post("/upload", function (req, res, next) {
  // 创建progress stream的实例
  var progress = progressStream({ length: "0" }); // 注意这里 length 设置为 '0'
  req.pipe(progress);
  progress.headers = req.headers;
  // 获取上传文件的真实长度（针对 multipart)
 
  progress.on("length", function nowIKnowMyLength(actualLength) {
    // console.log("文件大小: %s", actualLength);
    progress.setLength(actualLength);
  });
  // 获取上传进度
  let bar = null;
  progress.on("progress", function (obj) {
    
    // console.log(obj);
    // console.log("上传进度: %s", obj.percentage.toFixed(2) + "%");
    if (bar) {
      // bar.tick(obj.transferred);
      bar.increment();      
      bar.update(parseInt(obj.percentage), {filename:formatterSizeFromMB(obj.length)});
    } else {
      // bar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);
      bar = multibar.create(100, 0);
      // bar.start(obj.length, 0);
      // bar = new ProgressBar("  uploading [:bar] :rate/bps :percent :etas", {
      //   complete: "=",
      //   incomplete: " ",
      //   width: 20,
      //   total: obj.length,
      // });
    }
  });
  // 实际上传文件
  // upload.single('file')(progress, res, next);
  upload(progress, res, next);
});
app.post("/upload", function (req, res, next) {
  res.send({ msg: "ok" });
});

app.use(express.static(path.join(__dirname, "public/")));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false, limit: "10000kb" }));
app.listen(webconfig.port);
console.log("server listing on ", webconfig.port);



const formatterSizeFromMB = (bytes) => {
  if (bytes == 0) return "0 MiB";
  let k = 1024; //set base size
  let sizeStr = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; //size
  let i = 0; //Unit subscript and power
  for (let l = 0; l < 6; l++) {
    if (bytes / Math.pow(k, l) < 1) {
      break;
    }
    i = l;
  }
  let n = (bytes / Math.pow(k, i)).toFixed(0);
  let unit = sizeStr[i];
  return `${n}${unit}`;
};
